package admin

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"strconv"
	"strings"
	"sync"
	"tcsc/models"
	"tcsc/sword"
	"time"

	"github.com/astaxie/beego"
)

type Program struct {
	BaseController
}

func (c *Program) Get() {
	gid := c.Gid
	if real := models.Query(`select * from mt_program where gid=` + gid); real == nil {
		now := time.Now().Local().Format("2006-01-02 15:04:05")
		err := models.Exec(`insert into mt_program(name,gid,addtime,sort,status,img,intr,defaultsort,bgImg,mobileImg) 
			select name,` + gid + `,'` + now + `',sort,'0',img,intr,defaultsort,bgImg,mobileImg from mt_program where gid = 0`)
		if err != nil {
			beego.Debug(err)
			c.Ctx.Redirect(302, "/admin/index/index")
			return
		}
	}
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	// w = append(w, `a.status=1`)
	w = append(w, `a.gid=`+gid)
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.sort desc,a.addtime desc`
	sql := `select a.*,b.pathname from mt_program a left join mt_resources b on a.img=b.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_program a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["gid"] = c.Gid
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/program/index?`
	c.TplName = "admin/program/index.html"
}

func (c *Program) Post() {
	js := make(map[string]interface{})
	id := c.GetString("id")
	err := models.Exec(`update mt_program set status=abs(status-1) where id=` + id)
	if err != nil {
		beego.Debug("更改状态mt_program失败:", err)
		js["status"] = 0
	} else {
		js["status"] = 1
	}
	c.Data["json"] = js
	c.ServeJSON()
}

type ProgramAE struct {
	BaseController
}

func (c *ProgramAE) Get() {
	val := c.GetString("val")
	pids := strings.Replace(strings.Trim(strings.Join(c.GetStrings("pid"), ","), ","), ",,", ",", -1)
	gid := c.Gid
	id := c.GetString("id")
	input := c.Input()
	if id != "" {
		if info := models.Query(`select a.*,b.pathname from mt_program a left join mt_resources b on a.img=b.id where a.id=` + id); info != nil {
			bgImgpathname := models.Query(`select pathname from mt_resources where id=?`, info[0]["bgImg"])
			if bgImgpathname != nil {
				info[0]["bgImgpathname"] = bgImgpathname[0]["pathname"]
			}
			mobilepathname := models.Query(`select pathname from mt_resources where id=?`, info[0]["mobileImg"])
			if mobilepathname != nil {
				info[0]["mobilepathname"] = mobilepathname[0]["pathname"]
			}
			if info[0]["pid"] != nil {
				if pids != "" {
					pids = pids + "," + info[0]["pid"].(string)
					info[0]["pid"] = pids
				} else {

					pids = info[0]["pid"].(string)
				}
			}

			if input.Get("name") != "" {
				info[0]["name"] = input.Get("name")
			}
			if input.Get("intr") != "" {
				info[0]["intr"] = input.Get("intr")
			}
			if input.Get("img") != "" {
				info[0]["img"] = input.Get("img")
			}
			if input.Get("bgImg") != "" {
				info[0]["bgImg"] = input.Get("bgImg")
			}
			if input.Get("mobileImg") != "" {
				info[0]["mobileImg"] = input.Get("mobileImg")
			}
			if input.Get("activetime") != "" {
				info[0]["activetime"] = input.Get("activetime")
			}
			if input.Get("sort") != "" {
				info[0]["sort"] = input.Get("sort")
			}
			if strings.Replace(strings.Trim(strings.Join(c.GetStrings("cid"), ","), ","), ",,", ",", -1) != "" {
				info[0]["cid"] = strings.Replace(strings.Trim(strings.Join(c.GetStrings("cid"), ","), ","), ",,", ",", -1)
			}
			c.Data["info"] = info[0]

		} else {
			c.Ctx.Redirect(302, "/admin/program/index")
		}
	} else {
		var info = make(map[string]interface{})
		info["name"] = input.Get("name")
		info["intr"] = input.Get("intr")
		info["img"] = input.Get("img")
		info["bgImg"] = input.Get("bgImg")
		info["mobileImg"] = input.Get("mobileImg")
		info["activetime"] = input.Get("activetime")
		info["sort"] = input.Get("sort")
		info["cid"] = strings.Replace(strings.Trim(strings.Join(c.GetStrings("cid"), ","), ","), ",,", ",", -1)
		info["pid"] = pids
		c.Data["info"] = info
	}
	column := models.Query(`select id,name from mt_column where type='p' and status=1 and pid=0`)
	wg := sync.WaitGroup{}
	for index, vv := range column {
		var cids []string
		cids = append(cids, fmt.Sprint(vv["id"]))
		if len(cids) == 0 {
			continue
		}
		wg.Add(1)
		go func(v orm.Params, i int, ccids []string) {
			//beego.Debug(ccids)
			son := models.Query(`select id from mt_column where pid=` + v["id"].(string))
			for _, s1 := range son {
				ccids = append(cids, fmt.Sprint(s1["id"]))
				son2 := models.Query(`select id from mt_column where pid=` + s1["id"].(string))
				for _, s2 := range son2 {
					cids = append(cids, fmt.Sprint(s2["id"]))
				}
				s1["son"] = son2
			}
			cidss := strings.Join(ccids, ",")
			var sql = `select a.id,a.title 
				from mt_product a 
				left join mt_shop b on a.gid=b.id 
				where a.status=1 and a.censoring=1  and a.cid in(` + cidss + `)`
			if gid == "0" {
				sql += " and (a.gid=0 or (b.style=0 and b.status=1 and b.censoring=1))"
			} else {
				sql += " and a.gid=" + gid
			}
			if val != "" {
				if pids == "" || pids == "," {
					sql += " and a.title like '%" + val + "%'"
				} else {
					sql += " and (a.title like '%" + val + "%' or a.id in (" + pids + "))"
				}
				sql += " order by a.cid"
				column[i]["product"] = models.Query(sql)
			} else {
				if pids != "" && pids != "," {
					sql += " and a.id in (" + pids + ")"
					sql += " order by a.cid"
					column[i]["product"] = models.Query(sql)
				}
			}
			//beego.Debug(sql)
			//beego.Debug(column[i])
			wg.Done()
		}(vv, index, cids)
		//if len(cids) > 0 {
		//	son := models.Query(`select id from mt_column where pid=` + v["id"].(string))
		//	for _, s1 := range son {
		//		cids = append(cids, fmt.Sprint(s1["id"]))
		//		son2 := models.Query(`select id from mt_column where pid=` + s1["id"].(string))
		//		for _, s2 := range son2 {
		//			cids = append(cids, fmt.Sprint(s2["id"]))
		//		}
		//		s1["son"] = son2
		//	}
		//	cidss := strings.Join(cids, ",")
		//	var sql = `select a.id,a.title
		//		from mt_product a
		//		left join mt_shop b on a.gid=b.id
		//		where a.status=1 and a.censoring=1  and a.cid in(` + cidss + `)`
		//	if gid == "0" {
		//		sql += " and (a.gid=0 or (b.style=0 and b.status=1 and b.censoring=1))"
		//	} else {
		//		sql += " and a.gid=" + gid
		//	}
		//	if val != "" {
		//		if pids == "" || pids == "," {
		//			sql += " and a.title like '%" + val + "%'"
		//		} else {
		//			sql += " and (a.title like '%" + val + "%' or a.id in (" + pids + "))"
		//		}
		//		sql += " order by a.cid"
		//
		//		v["product"] = models.Query(sql)
		//	} else {
		//		if pids != "" && pids != "," {
		//			sql += " and a.id in (" + pids + ")"
		//			sql += " order by a.cid"
		//			v["product"] = models.Query(sql)
		//		}
		//	}
		//
		//}
	}
	wg.Wait()

	c.Data["column"] = column

	c.TplName = "admin/program/ae.html"
}
func (c *ProgramAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	if c.Gid == "0" && input.Get("id") != "" {
		name := input.Get("name")
		intr := input.Get("intr")
		img := input.Get("img")
		bgImg := input.Get("bgImg")
		mobileImg := input.Get("mobileImg")
		sort := input.Get("sort")
		defaultsort := input.Get("defaultsort")
		err := models.Exec(`update mt_program set name='` + name + `',intr='` + intr + `',img='` + img + `',sort='` + sort + `',bgImg='` + bgImg + `',mobileImg='` + mobileImg + `' where gid <> 0 and defaultsort=` + defaultsort)
		if err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
			return
		}
	}
	input.Set("cid", strings.Replace(strings.Trim(strings.Join(c.GetStrings("cid"), ","), ","), ",,", ",", -1))
	input.Set("pid", strings.Replace(strings.Trim(strings.Join(c.GetStrings("pid"), ","), ","), ",,", ",", -1))
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
		max := models.Query(`select max(defaultsort) as defaultsort from mt_program where gid=0`)[0]["defaultsort"]
		defaultsort, _ := strconv.Atoi(max.(string))
		defaultsort = defaultsort + 1
		beego.Debug(strconv.Itoa(defaultsort))
		input.Set("defaultsort", strconv.Itoa(defaultsort))

		if c.Gid == "0" {
			shop := models.Query(`select id from mt_shop where status=1 and censoring=1 and style=1`)
			for _, v := range shop {
				if models.Query(`select * from mt_program where gid=?`, v["id"]) != nil {
					name := input.Get("name")
					intr := input.Get("intr")
					img := input.Get("img")
					bgImg := input.Get("bgImg")
					mobileImg := input.Get("mobileImg")
					defaultsort := input.Get("defaultsort")
					gid := v["id"].(string)
					err := models.Exec(`insert into mt_program 
									(name,intr,img,bgImg,defaultsort,gid,mobileImg,status)
									values
									(?,?,?,?,?,?,?,0)`, name, intr, img, bgImg, defaultsort, gid, mobileImg)
					if err != nil {
						beego.Debug(err)
						c.Data["json"] = 0
						return
					}
				}
			}
		} else {
			input.Set("gid", c.Gid)
		}
	}
	input.Del("val")
	beego.Debug(input)
	if res, err := models.Save("mt_program", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 76
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type ProgramContent struct {
	BaseController
}

func (c *ProgramContent) Get() {
	id := c.GetString("id")
	if id != "" {
		if info := models.Query(`select a.*,b.pathname,c.pathname as pathname2 from mt_news a left join mt_resources b on a.img=b.id left join mt_resources c 
		on a.video=c.id where a.id=` + id); info != nil {
			for _, v := range info {
				keywords := fmt.Sprint(v["keywords"])
				keywords = strings.Trim(keywords, ",")
				if keywords == "" {
					keywords = "''"
				}
				v["keywords"] = models.Query(fmt.Sprintf(`select id,title from mt_keywords where id in(%v)`, keywords))
			}
			c.Data["info"] = info[0]
		} else {
			c.Ctx.Redirect(302, "/admin/news/index")
		}
	} else {
		c.Ctx.Redirect(302, "/admin/news/index")
	}
	c.TplName = "admin/news/content.html"
}
